package com.mongodemo.web.controller;

import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
import com.mongodemo.entity.Hobby;
import com.mongodemo.entity.Species;
import com.mongodemo.entity.User;
import com.mongodemo.service.UserService;


@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    
    @Autowired
    private GridFsTemplate gridFsTemplate;


    /**
     * 增加单个对象或者嵌套对象
     * @param user
     * @return
     */
    @RequestMapping("addUserInfo")
    public String addUser(@RequestBody User user){
    	Species s = new Species();
    	s.setMonery(10000);
    	s.setSort("A");
    	Species s1 = new Species();
    	s1.setMonery(20000);
    	s1.setSort("B");
    	List<Species> listS = new LinkedList<>();
    	listS.add(s);
    	listS.add(s1);
    	
    	Hobby h = new Hobby();
    	h.setSpecies(listS);
    	h.setU_id(user.getId());
    	h.setName("篮球");
    	h.setType("NBA");
    	List<Hobby> list = new LinkedList<>();
    	list.add(h);
    	user.setHobby(list);
    	
        userService.addUser(user);
       
        return "mongodb插入嵌套结构";
    }
    
    /**
     * 获取所有的文档
     * @return
     */
    @RequestMapping("getAllUser")
    public Object getUser() {
    	return userService.getUserAll().toString();
    }
    
    /**
     * 文件上传
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public Object uploadFile(HttpServletRequest request) throws Exception {
        Part part = request.getPart("file");
        // 获得提交的文件名
        String fileName = part.getSubmittedFileName();
        // 获得文件输入流
        InputStream ins = part.getInputStream();
        // 获得文件类型
        String contentType = part.getContentType();
        // 将文件存储到mongodb中,mongodb 将会返回这个文件的具体信息
        GridFSFile store = gridFsTemplate.store(ins, fileName, contentType);
        return store.toString();
    }
    
    /**
     * 文件下载
     * @param fileId
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/downloadFile")
    public void downloadFile(@RequestParam(name = "file_id") String fileId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Query query = Query.query(Criteria.where("_id").is(fileId));
        // 查询单个文件
        GridFSDBFile gfsfile = gridFsTemplate.findOne(query);
        if (gfsfile == null) {
            return;
        }
        String fileName = gfsfile.getFilename().replace(",", "");
        //处理中文文件名乱码
        if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||
                request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")
                || request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            //非IE浏览器的处理：
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        // 通知浏览器进行文件下载
        response.setContentType(gfsfile.getContentType());
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        gfsfile.writeTo(response.getOutputStream());
    }
 
    /**
     * 删除文件
     *
     * @param fileId
     * @return
     */
    @RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
    public Object deleteFile(@RequestParam(name = "file_id") String fileId) {
        Query query = Query.query(Criteria.where("_id").is(fileId));
        // 查询单个文件
        GridFSDBFile gfsfile = gridFsTemplate.findOne(query);
        if (gfsfile == null) {
            return "无文件删除";
        }
        gridFsTemplate.delete(query);
        return "删除成功";
    }
}
